package com.daocao.yfb.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;
import cn.beecloud.entity.BCReqParams;

import com.bumptech.glide.Glide;
import com.daocao.yfb.R;
import com.daocao.yfb.adapter.BuyTypeAdapter;
import com.daocao.yfb.api.Api;
import com.daocao.yfb.api.bean.OrderEditBean;
import com.daocao.yfb.api.model.BuyTypeModel;
import com.daocao.yfb.api.model.GoodsBuyBean;
import com.daocao.yfb.base.BaseActivity;
import com.daocao.yfb.constant.Const;
import com.daocao.yfb.event.SelectAccountEvent;
import com.daocao.yfb.util.Network;
import com.daocao.yfb.util.RxLifeUtil;
import com.daocao.yfb.util.ToastUtil;
import com.daocao.yfb.util.UI;
import com.daocao.yfb.util.Util;
import com.daocao.yfb.view.V19FrameLayout;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class SureOrderActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.img_icon)
    ImageView imgIcon;
    @BindView(R.id.btn_sub)
    ImageView btnSub;
    @BindView(R.id.txt_num_sec)
    TextView txtNumSec;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.btn_name)
    LinearLayout btnName;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.btn_buy)
    TextView btnBuy;
    @BindView(R.id.layout_bottom)
    LinearLayout layoutBottom;
    @BindView(R.id.txt_account)
    TextView txtAccount;
    @BindView(R.id.txt_one_money)
    TextView txtOneMoney;
    @BindView(R.id.txt_order_name)
    TextView txtOrderName;
    private ProgressDialog progressDialog;
    private PayHandler mHandler;
    private String toastMsg;
    private static final String WX_APP = "WX_APP";
    private static final String ALI_APP = "ALI_APP";
//    private static final String UN_APP = "UN_APP";
//    private static final String ACCOUNT = "ACCOUNT";

    private String selectWays;
    private Unbinder unbiner;
    private int number = 1;
    private BuyTypeAdapter adapter;
    private float OrderMoney = 0;
    private String id;
    private String relate_id;
    private String payId;
    private String order_number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sure_order);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtNumSec.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(UI.toString(txtNumSec))) {
                    number = 0;
                    txtMoney.setText("");
                    return;
                }
                number = UI.toInteger(txtNumSec);
                txtMoney.setText("￥" + (number * OrderMoney));
            }
        });
        String money = getIntent().getStringExtra("money");
        OrderMoney = Float.valueOf(money);
        String title = getIntent().getStringExtra("title");
        txtOrderName.setText(title);
        relate_id = getIntent().getStringExtra("relate_id");
        String relate_account = getIntent().getStringExtra("relate_account");
        order_number = getIntent().getStringExtra("order_number");

        if (!TextUtils.isEmpty(relate_account)) {
            txtName.setText(relate_account);
        }
        String order_num = getIntent().getStringExtra("num");
        if (!TextUtils.isEmpty(order_num)) {
            txtNumSec.setText(order_num);
        }
        id = getIntent().getStringExtra("id");
        String icon = getIntent().getStringExtra("icon");
        Glide.with(this).load(icon).into(imgIcon);
        txtOneMoney.setText("￥" + money);
        txtMoney.setText("￥" + Float.valueOf(money) * number);
        EventBus.getDefault().register(this);
        txtTitle.setText("确认订单");
        adapter = new BuyTypeAdapter(this);
        adapter.setOnChooseListener(new BuyTypeAdapter.OnChooseListener() {
            @Override
            public void onClick(String name, String id) {
                payId = id;
                selectWays = name;
            }
        });
        list.setAdapter(adapter);
        initPay();
        mHandler = new PayHandler(this);
        getPayWay();
    }

    public void getPayWay() {

        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();

        Api.api_service.getPayWay().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setPayWay(result.datas);
                });

    }

    public void getGoodsBuy(double payMoney) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        GoodsBuyBean bean = new GoodsBuyBean();
        bean.id = id;
        bean.num = number + "";
        bean.relate_id = relate_id;
        bean.payway_id = payId;
        Api.api_service.getGoodsBuy(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    order_number = result.datas.order_number;
                    goToPay("支付", Double.valueOf(result.datas.money_sum), result.datas.order_number);
                });

    }

    public void getOrderEdit() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        OrderEditBean bean = new OrderEditBean();
        bean.order_number = order_number;
        bean.num = number + "";
        bean.relate_id = relate_id;
        bean.payway_id = payId;
        Api.api_service.getOrderEdit(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    goToPay("支付", Double.valueOf(result.datas.money_sum), result.datas.order_number);
                });

    }

    private void setPayWay(List<BuyTypeModel> datas) {
        adapter.update(datas);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SelectAccountEvent event) {
        if (TextUtils.isEmpty(event.id)) {
            relate_id = "";
            txtName.setText("");
            return;
        }
        relate_id = event.id;
        txtName.setText(event.account);
    }


    private void initPay() {
        // 推荐在主Activity或application里的onCreate函数中初始化BeeCloud.
        if (Const.IS_DEBUG) {
            BeeCloud.setSandbox(true);

//        测试Appid和secret
            BeeCloud.setAppIdAndSecret("f4b08f6e-9c77-43d9-b829-e2bb796e3d77",
                    "6f2f8e53-5825-4629-90f5-728b07b06eb0");
        } else {
            BeeCloud.setSandbox(false);
            //     正式网Appid和secret
            BeeCloud.setAppIdAndSecret("956fb30c-0579-4469-aa31-64140d64e61c",
                    "17b96e5a-2c3d-4265-9308-ec4b50407f6e");
        }


        // 如果用到微信支付，在用到微信支付的Activity的onCreate函数里调用以下函数.
        // 第二个参数需要换成你自己的微信AppID.
//        wx8f9ffda903463ae8
        String initInfo = BCPay.initWechatPay(this, "wx8f9ffda903463ae8");
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("处理中，请稍候...");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
    }


    private void goToPay(String title, double money, String bill_no) {
//        Map<String, String> mapOptional = new Gson().fromJson(PayOrderitem.optional, new TypeToken<HashMap<String, String>>() {
//        }.getType());
//        Map<String, String> mapOptional = new HashMap<>();
//        mapOptional.put("action", PayOrderitem.optional.action);
        Map<String, String> mapOptional = new HashMap<>();
        mapOptional.put("app", "yunfenbao");
        if (selectWays.equals(ALI_APP)) {
//                    支付宝
            progressDialog.show();
//            BCPay.getInstance(PayTypeActivity.this).reqAliPaymentAsync(
//                    PayOrderitem.title,
//                    PayOrderitem.order_money * 100,
//                    PayOrderitem.notice_sn,
//                    mapOptional,
//                    bcCallback);
            BCPay.getInstance(this).reqAliPaymentAsync(
                    title,
                    (int) (money * 100),
                    bill_no,
                    mapOptional,
                    bcCallback);
        }
//        else if (selectWays.equals(UN_APP)) {
//            //银联支付
//            progressDialog.show();
//
//            BCPay.PayParams payParam = new BCPay.PayParams();
//
//            payParam.channelType = BCReqParams.BCChannelTypes.UN_APP;
//
//            //商品描述, 32个字节内, 汉字以2个字节计
//            payParam.billTitle = title;
//
//            //支付金额，以分为单位，必须是正整数
//            payParam.billTotalFee = (int) (money * 100);
//
//            //商户自定义订单号
//            payParam.billNum = bill_no;
////            payParam.analysis = mapOptional;
//            // 设置本次订单的异步回调地址（慎重设置，以免造成丢单），不设置则使用APP设置的全局webhook地址
////            payParam.notifyUrl = "https://apihz.beecloud.cn/1/pay/webhook/receiver/c5d1cba1-5e3f-4ba0-941d-9b0a371fe719";
//            payParam.notifyUrl = Const.SERVER_API_URL + "/callback/beecloud";
//            BCPay.getInstance(this).reqPaymentAsync(payParam,
//                    bcCallback);
//
//        }
        else if (selectWays.equals(WX_APP)) {
//                    微信
            progressDialog.show();
            //对于微信支付, 手机内存太小会有OutOfResourcesException造成的卡顿, 以致无法完成支付
            //这个是微信自身存在的问题
//            Log.i("dasdasddas", BCPay.isWXAppInstalledAndSupported() + "aa" + BCPay.isWXPaySupported());
            if (BCPay.isWXAppInstalledAndSupported() &&
                    BCPay.isWXPaySupported()) {

//                BCPay.getInstance(this).reqWXPaymentAsync(
//                        PayOrderitem.title,               //订单标题
//                        PayOrderitem.order_money * 100,  //金额
//                        PayOrderitem.notice_sn,  //订单流水号
//                        mapOptional,            //扩展参数(可以null)
//                        bcCallback);            //支付完成后回调入口
                BCPay.getInstance(this).reqWXPaymentAsync(
                        title,               //订单标题
                        (int) (money * 100),  //金额
                        bill_no,  //订单流水号
                        mapOptional,            //扩展参数(可以null)
                        bcCallback);            //支付完成后回调入口

            } else {
                ToastUtil.makeText(this,
                        "您尚未安装微信或者安装的微信版本不支持").show();
                progressDialog.dismiss();
            }
        }
    }

    private static class PayHandler extends Handler {
        WeakReference<SureOrderActivity> mActivityReference;

        PayHandler(SureOrderActivity activity) {
            mActivityReference = new WeakReference<SureOrderActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final SureOrderActivity activity = mActivityReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        //如果用户手机没有安装银联支付控件,则会提示用户安装
                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setTitle("提示");
                        builder.setMessage("完成支付需要安装或者升级银联支付控件，是否安装？");

                        builder.setNegativeButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
//                                        UPPayAssistEx.installUPPayPlugin(activity);
                                        dialog.dismiss();
                                    }
                                });

                        builder.setPositiveButton("取消",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        builder.create().show();
                        break;
                    case 2:
                        Toast.makeText(activity, activity.toastMsg, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }


    //支付结果返回入口
    private BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(final BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            //此处关闭loading界面
            progressDialog.dismiss();

            //根据你自己的需求处理支付结果
            String result = bcPayResult.getResult();
            /*
              注意！
              所有支付渠道建议以服务端的状态金额为准，此处返回的RESULT_SUCCESS仅仅代表手机端支付成功
            */
            Message msg = mHandler.obtainMessage();
            //单纯的显示支付结果
            msg.what = 2;
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "1", notice_sn);
                    }
                });
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();

                /**
                 * 你发布的项目中不应该出现如下错误，此处由于支付宝政策原因，
                 * 不再提供支付宝支付的测试功能，所以给出提示说明
                 */
                if (bcPayResult.getErrMsg().equals("PAY_FACTOR_NOT_SET") &&
                        bcPayResult.getDetailInfo().startsWith("支付宝参数")) {
                    toastMsg = "支付失败：由于支付宝政策原因，故不再提供支付宝支付的测试功能，给您带来的不便，敬请谅解";
                }

                /**
                 * 以下是正常流程，请按需处理失败信息
                 */

                if (bcPayResult.getErrMsg().equals(BCPayResult.FAIL_PLUGIN_NOT_INSTALLED)) {
                    //银联需要重新安装控件
                    msg.what = 1;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        getReportResult(money, "2", notice_sn);
                    }
                });

            } else if (result.equals(BCPayResult.RESULT_UNKNOWN)) {
                //可能出现在支付宝8000返回状态
                toastMsg = "订单状态未知";
            } else {
                toastMsg = "invalid return";
            }

            mHandler.sendMessage(msg);

            /*
            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());

                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                getBillInfoByID(bcPayResult.getId());
            }
            */
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        BCPay.detachWechat();
        bcCallback = null;
        mHandler = null;
        //清理当前的activity引用
        BCPay.clear();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_back, R.id.btn_sub, R.id.btn_add, R.id.btn_buy, R.id.btn_name})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_sub:
                if (number <= 1) {
                    return;
                }
                number--;
                txtMoney.setText("￥" + (int) (number * OrderMoney));
                txtNumSec.setText(number + "");
                break;
            case R.id.btn_add:
                number++;
                txtMoney.setText("￥" + (int) (number * OrderMoney));
                txtNumSec.setText(number + "");
                break;
            case R.id.btn_buy:
                if (TextUtils.isEmpty(selectWays)) {
                    ToastUtil.makeText(this, "请选择支付方式");
                    return;
                }
                if (TextUtils.isEmpty(order_number)) {
                    Double payMoney = Double.valueOf(UI.toString(txtMoney).replace("￥", ""));
                    getGoodsBuy(payMoney);
                } else {
//                    Double payMoney = Double.valueOf(UI.toString(txtMoney).replace("￥", ""));
//                    goToPay("支付", payMoney, order_number);
                    getOrderEdit();
                }
                break;
            case R.id.btn_name:
                Util.startActivity(this, SelectAccountActivity.class);
                break;
        }
    }
}
